package com.blog.common.mapper.handler;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blog.common.core.utils.PageUtils;
import com.blog.common.domain.adapter.ConvertAdapter;
import lombok.NonNull;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

import static com.blog.common.core.constant.ServiceConst.DEFAULT_NUM;
import static com.blog.common.core.constant.ServiceConst.DEFAULT_SIZE;
import static com.blog.common.core.constant.CommonConstants.PAGE_NUM;
import static com.blog.common.core.constant.CommonConstants.PAGE_SIZE;

/**
 * 分页拦截器
 * 请求分页参数拦截
 *
 * @author Valerie
 * @date 2023/2/18
 **/
public class PageableHandlerInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {
        // 页面码
        String pageNum = Optional.ofNullable(request.getParameter(PAGE_NUM)).orElse(DEFAULT_NUM);
        // 页面大小
        String pageSize = Optional.ofNullable(request.getParameter(PAGE_SIZE)).orElse(DEFAULT_SIZE);

        PageUtils.setCurrentPage(new Page<>(Long.parseLong(pageNum), Long.parseLong(pageSize)));

        return true;
    }


    @Override
    public void afterCompletion(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler, Exception ex) {
        // 清空threadLocal
        PageUtils.remove();
        ConvertAdapter.clear();
    }
}
